﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Management;
using System.Diagnostics;
using System.ComponentModel;
using Microsoft.Web.Administration;
using Microsoft.Web.Management;
using System.Security;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using System.Xml;
using System.Data.SqlClient;

namespace WindowsFormsApplication2
{
    //Extended the WebClient class to include webquest timeout. 
    public class TimedWebClient : WebClient
    {
        public int Timeout { get; set; }
        public TimedWebClient()
        {

            this.Timeout = 60000;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var objWebRequest = base.GetWebRequest(address);
            objWebRequest.Timeout = this.Timeout;
            return objWebRequest;
        }
    }   
    class wmi2
    {

        private const string MSSystem = "\\C$\\SecretAgent\\wwwRoot\\IncludeDirectories\\Mastersite\\System\\";

        static private void RunProcess(string ServerName, string process)
        {
            object[] theProcessToRun = { process };
            ManagementClass mClass = new ManagementClass(@"\\" + ServerName + @"\root\cimv2:Win32_Process");
            object result = mClass.InvokeMethod("Create", theProcessToRun);
        }

        //This will reset the IIS for the server. 
        static public Boolean IISReset(string ServerName)
        {
            try
            {
                RunProcess(ServerName, "iisreset.exe");
                return true;
            }
            catch
            {
                return false;
            }
        }

        //This takes server offline
        static public Boolean ServerOffline(string ServerName)
        {
            try
            {
                ServerName = "\\\\" + ServerName;
                File.SetAttributes(ServerName + MSSystem + "Status.aspx", FileAttributes.Normal);
                File.Delete(ServerName + MSSystem + "Status.aspx");
                File.Copy(ServerName + MSSystem + "StatusFail.aspx", ServerName + MSSystem + "Status.aspx");
                return true;
            }
            catch
            {
                return false;
            }
        }

        //This brings server online
        static public Boolean ServerOnline(string ServerName)
        {
            try
            {
                ServerName = "\\\\" + ServerName;
                File.SetAttributes(ServerName + MSSystem + "Status.aspx", FileAttributes.Normal);
                File.Delete(ServerName + MSSystem + "Status.aspx");
                File.Copy(ServerName + MSSystem + "StatusOriginal.aspx", ServerName + MSSystem + "Status.aspx");
                return true;

            }
            catch
            {
                return false;
            }
        }

        //This method export registry to file. 
        static public Boolean ExportReg(string RegKey, string SavePath, string ServerName)
        {
            string path = "\"" + SavePath + "\"";
            string key = "\"" + RegKey + "\"";
            string process = "regedit.exe /e " + path + " " + key + "";
            try
            {
                RunProcess(ServerName, process);
                return true;
            }
            catch
            {
                return false;
            }
        }

        //This method imports the registry file 
        static public Boolean ImportReg(string RegKey, string SavePath, string ServerName)
        {
            string path = "\"" + SavePath + "\"";
            string key = "\"" + RegKey + "\"";
            string process = "regedit.exe /s " + path + " " + key + "";
            try
            {
                RunProcess(ServerName, process);
                return true;
            }
            catch
            {
                return false;
            }
        }
     
        //Pulls the performance counter for that specfic server. 
        public static string PerformanceMonitor(string FullComputerName, string Name, string PW, string counter)
        {

            string ReturnCounter = "";
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = Name;
                connection.Password = PW;
                connection.Authority = "ntlmdomain:ENEIGHBORHOODS";

                ManagementScope scope = new ManagementScope(
                    "\\\\" + FullComputerName + "\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM Win32_PerfRawData_ASPNET_ASPNETApplications");
                ObjectQuery query1 = new ObjectQuery(
                    "SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
                ObjectQuery query2 = new ObjectQuery(
                    "SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk");

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);



                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (counter == "1")
                    {
                        ReturnCounter = (/*"AnonymousRequests : {0}"*/ queryObj["AnonymousRequests"].ToString());
                        Debug.WriteLine(/*"AnonymousRequests : {0}"*/ queryObj["AnonymousRequests"]);
                        break;
                    }

                    if (counter == "2")
                    {
                        ReturnCounter = (/*"RequestExecutionTime : {0}"*/ queryObj["RequestExecutionTime"].ToString());
                        break;
                    }

                    if (counter == "3")
                    {
                        ReturnCounter = (/*"RequestWaitTime : {0}"*/ queryObj["RequestWaitTime"].ToString());
                        break;
                    }

                    if (counter == "4")
                    {
                        ReturnCounter = /*"AnonymousRequestsPerSec : {0}"*/ queryObj["AnonymousRequestsPerSec"].ToString();
                        break;
                    }

                    if (counter == "5")
                    {
                        ReturnCounter =/* "SessionActive : {0}"*/  queryObj["SessionActive"].ToString();
                        break;
                    }
                }

               

                if (counter == "6")
                {
                    ManagementObjectSearcher searcher3 = new ManagementObjectSearcher(scope, query2);


                    foreach (ManagementObject queryObj in searcher3.Get())
                    {

                        {
                            ReturnCounter =/*"AvgDiskQueueLength : {0} "*/ queryObj["AvgDiskQueueLength"].ToString();
                            break;
                        }
                    }
                }
            }




            catch (ManagementException err)
            {

                ReturnCounter = err.Message.ToString();
            }

            return ReturnCounter;
        }

        //Connects to the Database NFDBCONFIF\\CONFIG
        public static List<string> Datapod()
        {
            //Initating a new list for the ilist the combo box takes. 
            List<string> VBAT3 = new List<string>();
            string queryString =
                        "usp_Get_WebDronePair;";
            SqlConnection thisconnection = new SqlConnection("Data Source=NFDBCONFIG\\CONFIG;" + "Initial Catalog=Customers;" + "user id=rciapplicationsnew;" + "password=H7hr89jz?");

            {
                
                SqlCommand command =
                    new SqlCommand(queryString, thisconnection);
                thisconnection.Open();

                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    
                VBAT3.Add(reader["WebServerName"].ToString());
         
                }

                thisconnection.Close();

            }
            return VBAT3;
        }

        //Web Server Status. 
        public static string CheckPool(string FullComputerName)
        {
           string ResponseWebSite = " ";
           string WebSiteLink;
           string html = " ";


           try
           {
               
               WebSiteLink = "http://" + FullComputerName.ToLower() + "/system/status.aspx";
               html = new TimedWebClient { Timeout = 5000 }.DownloadString(WebSiteLink);
  
           }

           catch (WebException)
           {
               WebSiteLink = "http://www." + FullComputerName.ToLower() + ".com/system/status.aspx";

               html = new TimedWebClient { Timeout = 150000 }.DownloadString(WebSiteLink);
           }
           
            
         
            try
            {
               

                int intPos = html.IndexOf("All OK");

                if (html.Contains("True"))
                {
                    ResponseWebSite = "OK";
                }

                else if(html.Contains("False"))
                {
                    ResponseWebSite = "NOT OK";          
                }
            }
              
            catch
            {
                ResponseWebSite = "Not Reachable";           
            }

            return ResponseWebSite;
          
        }

        //Check if Attentnion is need to a specicifc server. 
        public static string CheckAttenion(string FullComputerName)
        {
            string ResponseWebSite = " ";
            string WebSiteLink;
            string html = " ";
            try
            {

                WebSiteLink = "http://" + FullComputerName.ToLower() + "/system/status.aspx";
                html = new TimedWebClient { Timeout = 5000 }.DownloadString(WebSiteLink);

            }
            catch (WebException)
            {
                WebSiteLink = "http://www." + FullComputerName.ToLower() + ".com/system/status.aspx";

                html = new TimedWebClient { Timeout = 150000 }.DownloadString(WebSiteLink);
            }
           
            try
            {
                

                int intPos = html.IndexOf("Needs Attention");

                if (html.Contains("Yes"))
                {
                    ResponseWebSite = "Yes";
                }

                else if (html.Contains("No"))
                {
                    ResponseWebSite = "No";
                }
            }

            catch
            {
                ResponseWebSite = "Not Reachable";
            }

            return ResponseWebSite;

        }
      
    }
    
  

}
